import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

import '../config/app_colors.dart';
import '../config/app_url_address.dart';
import '../utils/JoyActionService.dart';
import '../utils/JoyCacheManager.dart';
import '../utils/JoyUrlLauncherService.dart';
import '../utils/route_utils.dart';
import 'JoyPrivacyWebPage.dart';

///class JoyAboutUsPage extends StatefulWidget{

class JoyAboutUsPage extends StatefulWidget {
  const JoyAboutUsPage({Key? key}) : super(key: key);

  @override
  State<JoyAboutUsPage> createState() => _JoyAboutUsPageState();
}

class _JoyAboutUsPageState extends State<JoyAboutUsPage> {
  String _appVersion = "1.0.0";
  String _appName = "Litbuy Sheets";
  String _cacheSize = "0.0MB";

  @override
  void initState() {
    super.initState();
    _getAppInfo();
    _calculateCacheSize();
  }

  Future<void> _getAppInfo() async {
    try {
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      setState(() {
        _appVersion = packageInfo.version;

      });
    } catch (e) {
      debugPrint("获取应用信息错误: $e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back();
        return false;
      },
      child: Scaffold(
        backgroundColor: Color(0xFFF8F9FA),
        appBar: AppBar(
          backgroundColor: AppColors.backHomeYellowGround,
          title: Text(
            "About Us",
            style: TextStyle(
              color: AppColors.primary,
              fontSize: 16.sp,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
        body: CustomScrollView(
          slivers: [
            // 自定义 AppBar
            // SliverAppBar(
            //   expandedHeight: 80.h,
            //   floating: false,
            //   pinned: true,
            //   backgroundColor: AppColors.backHomeYellowGround,
            //
            //   flexibleSpace: FlexibleSpaceBar(
            //     title: Text(
            //       "About Us",
            //       style: TextStyle(
            //         color: Colors.white,
            //         fontSize: 16.sp,
            //         fontWeight: FontWeight.w600,
            //       ),
            //     ),
            //     centerTitle: true,
            //     background: Container(
            //       decoration: BoxDecoration(
            //         gradient: LinearGradient(
            //           begin: Alignment.topLeft,
            //           end: Alignment.bottomRight,
            //           colors: [
            //             AppColors.backHomeYellowGround,
            //             AppColors.backHomeYellowGround,
            //             AppColors.backHomeYellowGround,
            //           ],
            //         ),
            //       ),
            //     ),
            //   ),
            // ),
            
            // 内容区域
            SliverToBoxAdapter(
              child: Container(
                margin: EdgeInsets.all(16.w),
                child: Column(
                  children: [
                    // 功能卡片
                    _buildModernCard(
                      child: Column(
                        children: [
                      
                          _buildModernMenuItem(
                            icon: Icons.privacy_tip,
                            title: 'Privacy Policy',
                            subtitle: 'Learn about our privacy practices',
                            onTap: () {
                              JoyNavUtils().to(JoyPrivacyWebPage(
                                url: joyprivacyUrl,
                                title: "Privacy Policy",
                              ));
                            },
                          ),
                          _buildDivider(),
                          _buildModernMenuItem(
                            icon: Icons.assignment,
                            title: 'User Agreement',
                            subtitle: 'Read our terms and conditions',
                            onTap: () {
                              JoyNavUtils().to(JoyPrivacyWebPage(
                                url: joyUserPrivacyUrl,
                                title: "User Agreement",
                              ));
                            },
                          ),
                          _buildDivider(),
                          _buildModernMenuItem(
                            icon: Icons.cleaning_services_outlined,
                            title: 'Clear Cache',
                            subtitle: 'Free up storage space ($_cacheSize)',
                            onTap: () => _clearAppCache(),
                          ),
                        ],
                      ),
                    ),
                    
                    SizedBox(height: 16.h),
                    
                    // 应用信息卡片
                    _buildModernCard(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'App Information',
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: FontWeight.w600,
                              color: Colors.black87,
                            ),
                          ),
                          SizedBox(height: 12.h),
                          // _buildInfoRow('App Name', _appName),
                          SizedBox(height: 8.h),
                          _buildInfoRow('Version', _appVersion),
                          // SizedBox(height: 12.h),
                          // _buildInfoRow('Build', 'Release'),
                          // SizedBox(height: 12.h),
                          // _buildInfoRow('Platform', 'Flutter'),
                        ],
                      ),
                    ),
                  
                    SizedBox(height: 20.h),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 现代化卡片容器
  Widget _buildModernCard({required Widget child}) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, 4),
            spreadRadius: 0,
          ),
        ],
        border: Border.all(
          color: Colors.grey.withOpacity(0.1),
          width: 1,
        ),
      ),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: child,
      ),
    );
  }

  // 现代化菜单项
  Widget _buildModernMenuItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12.r),
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 8.h),
        child: Row(
          children: [
            // 图标容器
            Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                color: AppColors.primary.withOpacity(0.1),
                borderRadius: BorderRadius.circular(10.r),
              ),
              child: Icon(
                icon,
                color: AppColors.primary,
                size: 18.sp,
              ),
            ),
            SizedBox(width: 12.w),
            // 文字内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                ],
              ),
            ),
            // 箭头图标
            Icon(
              Icons.arrow_forward_ios,
              size: 12.sp,
              color: Colors.grey[400],
            ),
          ],
        ),
      ),
    );
  }

  // 分割线
  Widget _buildDivider() {
    return Container(
      margin: EdgeInsets.symmetric(vertical: 6.h),
      height: 0.5.h,
      color: Colors.grey.withOpacity(0.1),
    );
  }

  // 信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.grey[600],
            fontWeight: FontWeight.w500,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.black87,
            fontWeight: FontWeight.w600,
          ),
        ),
      ],
    );
  }

  Future<void> aaclaunchTelegramUrl() async {
    bool success = await JoyUrlLauncherService.launchTelegramUrl("TrendyHub2");

    if (!success && mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text("Could not launch Telegram. Please check if you have a browser installed."),
          duration: Duration(seconds: 3),
        ),
      );
    }
  }

  // 现代化联系项目
  Widget _buildModernContactItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required String value,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(12.r),
      child: Container(
        padding: EdgeInsets.all(16.w),
        decoration: BoxDecoration(
          color: Colors.grey[50],
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color: Colors.grey.withOpacity(0.2),
            width: 1,
          ),
        ),
        child: Row(
          children: [
            // 图标
            Container(
              width: 48.w,
              height: 48.w,
              decoration: BoxDecoration(
                color: Color(0xFFFF6B35).withOpacity(0.1),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Icon(
                icon,
                color: Color(0xFFFF6B35),
                size: 24.sp,
              ),
            ),
            SizedBox(width: 16.w),
            // 内容
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w600,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 2.h),
                  Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.grey[600],
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    value,
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Color(0xFFFF6B35),
                      fontWeight: FontWeight.w500,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            // 箭头
            Icon(
              Icons.arrow_forward_ios,
              size: 16.sp,
              color: Colors.grey[400],
            ),
          ],
        ),
      ),
    );
  }

  void _showFeatureNotImplementedDialog(String featureName) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: Colors.transparent,
        contentPadding: EdgeInsets.zero,
        content: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.r),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 20,
                offset: Offset(0, 10),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 标题区域
              Container(
                padding: EdgeInsets.all(24.w),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20.r),
                    topRight: Radius.circular(20.r),
                  ),
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [
                      Color(0xFFFF6B35),
                      Color(0xFFFF8C60),
                    ],
                  ),
                ),
                child: Row(
                  children: [
                    Container(
                      width: 40.w,
                      height: 40.w,
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(10.r),
                      ),
                      child: Icon(
                        Icons.support_agent,
                        color: Colors.white,
                        size: 20.sp,
                      ),
                    ),
                    SizedBox(width: 12.w),
                    Expanded(
                      child: Text(
                        'Contact Us',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              
              // 内容区域
              Padding(
                padding: EdgeInsets.all(24.w),
                child: Column(
                  children: [
                    _buildModernContactItem(
                      icon: Icons.chat,
                      title: "Discord",
                      subtitle: "Join our community",
                      value: "https://discord.gg/qdyjDrhhS5",
                      onTap: () async {
                        const url = "https://discord.gg/qdyjDrhhS5";
                        await JoyActionService.LitaunchDiscordApp(url);
                      },
                    ),
                    SizedBox(height: 16.h),
                    _buildModernContactItem(
                      icon: Icons.telegram,
                      title: "Telegram",
                      subtitle: "Direct messaging",
                      value: "https://t.me/TrendyHub2",
                      onTap: () async {
                        await aaclaunchTelegramUrl();
                      },
                    ),
                    SizedBox(height: 16.h),
                    _buildModernContactItem(
                      icon: Icons.phone,
                      title: "WhatsApp",
                      subtitle: "Business inquiries",
                      value: "+44 7545 529 811",
                      onTap: () {
                        Clipboard.setData(const ClipboardData(text: "+44 7545 529 811"));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text("WhatsApp number copied to clipboard"),
                            backgroundColor: Color(0xFFFF6B35),
                          ),
                        );
                      },
                    ),
                    SizedBox(height: 16.h),
                    _buildModernContactItem(
                      icon: Icons.email,
                      title: "Email",
                      subtitle: "General support",
                      value: "alexander.invincible1997@gmail.com",
                      onTap: () {
                        Clipboard.setData(const ClipboardData(text: "alexander.invincible1997@gmail.com"));
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text("Email address copied to clipboard"),
                            backgroundColor: Color(0xFFFF6B35),
                          ),
                        );
                      },
                    ),
                  ],
                ),
              ),
              
              // 关闭按钮
              Container(
                padding: EdgeInsets.fromLTRB(24.w, 0, 24.w, 24.w),
                child: SizedBox(
                  width: double.infinity,
                  height: 48.h,
                  child: ElevatedButton(
                    onPressed: () => Navigator.pop(context),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Color(0xFFFF6B35),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      elevation: 0,
                    ),
                    child: Text(
                      'Close',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 计算缓存大小
  Future<void> _calculateCacheSize() async {
    try {
      final cacheInfo = await JoyCacheManager.getCacheInfo();
      if (mounted) {
        setState(() {
          _cacheSize = "${cacheInfo['sizeInMB']}MB";
        });
      }
    } catch (e) {
      debugPrint("Error calculating cache size: $e");
      if (mounted) {
        setState(() {
          _cacheSize = "0.0MB";
        });
      }
    }
  }

  // 清理缓存
  Future<void> _clearAppCache() async {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(16.r),
        ),
        title: Text(
          'Clear Cache',
          style: TextStyle(
            fontSize: 18.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        content: Text('Are you sure you want to clear the application cache? This will delete temporary files and image cache. Current cache size: $_cacheSize'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text(
              'Cancel',
              style: TextStyle(
                color: Colors.grey[600],
              ),
            ),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.pop(context);
              // 显示加载对话框
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) => AlertDialog(
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16.r),
                  ),
                  content: Row(
                    children: [
                      const CircularProgressIndicator(
                        valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFFF6B35)),
                      ),
                      SizedBox(width: 16.w),
                      const Text('Clearing cache...'),
                    ],
                  ),
                ),
              );
              await _clearCache();
              _showSnackBar('Cache cleared successfully');
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: AppColors.primary,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8.r),
              ),
            ),
            child: Text(
              'Confirm',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 清除缓存的方法
  Future<void> _clearCache() async {
    try {
      // 使用自定义缓存管理器清理缓存
      await JoyCacheManager.clearAllCache();

      // 清理系统缓存目录
      final tempDir = await getTemporaryDirectory();
      final appDir = await getApplicationCacheDirectory();

      if (tempDir.existsSync()) {
        tempDir.listSync(recursive: true, followLinks: false).forEach((FileSystemEntity entity) {
          if (entity is File) {
            try {
              entity.deleteSync();
            } catch (e) {
              // Ignore files that failed to delete
            }
          }
        });
      }

      if (appDir.existsSync()) {
        appDir.listSync(recursive: true, followLinks: false).forEach((FileSystemEntity entity) {
          if (entity is File) {
            try {
              entity.deleteSync();
            } catch (e) {
              // Ignore files that failed to delete
            }
          }
        });
      }

      await _calculateCacheSize();
      Navigator.pop(context); // 关闭加载对话框
    } catch (e) {
      debugPrint("Error clearing cache: $e");
      Navigator.pop(context);
    }
  }

  // 显示提示消息
  void _showSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: const Color(0xFFFF6B35),
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.r),
        ),
      ),
    );
  }
}